/**
 * Simple REST client for interaction with caw web service
 * 
 * @author: dino.keco
 * @version 0.1
 * 
 */

var CAW_CLIENT = namespace("caw.ws.client");

/* constants */
CAW_CLIENT.WS_URL = 'http://localhost:8080/caw-ws/rest';
CAW_CLIENT.TABLES_RESOURCE = "/tables";
CAW_CLIENT.ACTION_RESOURCE = "/actions";
CAW_CLIENT.ROWS_RESOURCE = "/rows";

CAW_CLIENT.getTableDescriptors = function(onSuccessFunction, onFailureFunction) {
	var tablesURL = CAW_CLIENT.WS_URL + CAW_CLIENT.TABLES_RESOURCE;
	CAW_CLIENT.executeHTTPmethod(tablesURL, "GET", null, onSuccessFunction, onFailureFunction)
}

CAW_CLIENT.getTableDescriptor = function(tableName, onSuccessFunction, onFailureFunction) {
	var tableURL = CAW_CLIENT.WS_URL + CAW_CLIENT.TABLES_RESOURCE + "/" + tableName;
	CAW_CLIENT.executeHTTPmethod(tableURL, "GET", null, onSuccessFunction, onFailureFunction)
}

CAW_CLIENT.getTableDescriptor = function(tableName, onSuccessFunction, onFailureFunction) {
	var tableURL = CAW_CLIENT.WS_URL + CAW_CLIENT.TABLES_RESOURCE + "/" + tableName;
	CAW_CLIENT.executeHTTPmethod(tableURL, "GET", null, onSuccessFunction, onFailureFunction)
}

CAW_CLIENT.scan = function(tableName, startKey, endKey, columns, versions, timestamp, onSuccessFunction, onFailureFunction){
	var scanURL = CAW_CLIENT.WS_URL + CAW_CLIENT.TABLES_RESOURCE + "/" + tableName + CAW_CLIENT.ROWS_RESOURCE;
	CAW_CLIENT.executeHTTPmethod(scanURL, "GET", null, onSuccessFunction, onFailureFunction)
}

CAW_CLIENT.getRecordsMultiget = function(tableName, versions, timestamp, rowkeys, columns, onSuccessFunction, onFailureFunction) {
	var tableURL = CAW_CLIENT.WS_URL + CAW_CLIENT.TABLES_RESOURCE + "/" + tableName + CAW_CLIENT.ROWS_RESOURCE + "?";

	// add row key parameters
	for ( var i = 0; i < rowkeys.length; i++) {
		tableURL = tableURL + "rowkey=" + rowkeys[i];
		if (i + 1 != rowkeys.length) {
			tableURL = tableURL + "&"
		}
	}

	// add columns parameters
	if (columns != null && columns != "") {
		tableURL = tableURL + "&"
		for ( var i = 0; i < columns.length; i++) {
			tableURL = tableURL + "column=" + columns[i];
			if (i + 1 != columns.length) {
				tableURL = tableURL + "&"
			}
		}
	}
	if (versions != null && versions != "") {
		tableURL = tableURL + "&" + "maxversion=" + versions;
	}
	if (timestamp != null && timestamp != "") {
		tableURL = tableURL + "&" + "timestamp=" + timestamp;
	}
	CAW_CLIENT.executeHTTPmethod(tableURL, "GET", null, onSuccessFunction, onFailureFunction)
}

CAW_CLIENT.executeHTTPmethod = function(url, methodType, body, onSuccessFunction, onFailureFunction) {
	$.ajax({
		url : url,
		type : methodType,
		processdata : false,
		data : body,
		dataType : "json",
		contentType : "application/json; charset=utf-8",

		success : function(data) {
			onSuccessFunction(data);
		},

		error : function(XMLHttpRequest, textStatus, errorThrown) {
			onFailureFunction(XMLHttpRequest, textStatus, errorThrown);
		}
	});
}